package com.tjy.web.controller.system;

import java.util.Date;
import java.util.List;
import java.util.Set;

import com.tjy.common.constant.CacheConstants;
import com.tjy.common.core.redis.RedisCache;
import com.tjy.common.utils.PhoneUtils;
import com.tjy.framework.web.service.SmsService;
import org.apache.commons.lang3.RandomStringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import com.tjy.common.constant.Constants;
import com.tjy.common.core.domain.AjaxResult;
import com.tjy.common.core.domain.entity.SysMenu;
import com.tjy.common.core.domain.entity.SysUser;
import com.tjy.common.core.domain.model.LoginBody;
import com.tjy.common.core.domain.model.LoginUser;
import com.tjy.common.core.text.Convert;
import com.tjy.common.utils.DateUtils;
import com.tjy.common.utils.SecurityUtils;
import com.tjy.common.utils.StringUtils;
import com.tjy.framework.web.service.SysLoginService;
import com.tjy.framework.web.service.SysPermissionService;
import com.tjy.framework.web.service.TokenService;
import com.tjy.system.service.ISysConfigService;
import com.tjy.system.service.ISysMenuService;

import java.util.concurrent.TimeUnit;

/**
 * 登录验证
 *
 * @author tjy
 */
@RestController
public class SysLoginController {
    @Autowired
    private SysLoginService loginService;

    @Autowired
    private ISysMenuService menuService;

    @Autowired
    private SysPermissionService permissionService;

    @Autowired
    private TokenService tokenService;

    @Autowired
    private ISysConfigService configService;

    @Autowired
    private RedisCache redisCache;

    @Autowired
    private SmsService smsService;

    /**
     * 登录方法
     *
     * @param loginBody 登录信息
     * @return 结果
     */
    @PostMapping("/login")
    public AjaxResult login(@RequestBody LoginBody loginBody) {
        AjaxResult ajax = AjaxResult.success();
        // 生成令牌
        String token = null;

        // 判断是手机号登录还是用户名密码登录
        if (StringUtils.isNotEmpty(loginBody.getPhoneNum()) && StringUtils.isNotEmpty(loginBody.getSmsCode())) {
            // 手机号验证码登录
            token = loginService.loginByPhone(loginBody.getPhoneNum(), loginBody.getSmsCode());
        } else {
            // 原有用户名密码登录
            token = loginService.login(loginBody.getUsername(), loginBody.getPassword(),
                    loginBody.getCode(), loginBody.getUuid(), loginBody.getPhoneNum(), loginBody.getLongitude(),loginBody.getLatitude());
        }

        ajax.put(Constants.TOKEN, token);

        return ajax;
    }

    /**
     * 获取用户信息
     *
     * @return 用户信息
     */
    @GetMapping("getInfo")
    public AjaxResult getInfo() {
        LoginUser loginUser = SecurityUtils.getLoginUser();
        SysUser user = loginUser.getUser();
        // 角色集合
        Set<String> roles = permissionService.getRolePermission(user);
        // 权限集合
        Set<String> permissions = permissionService.getMenuPermission(user);
        if (!loginUser.getPermissions().equals(permissions)) {
            loginUser.setPermissions(permissions);
            tokenService.refreshToken(loginUser);
        }
        AjaxResult ajax = AjaxResult.success();
        ajax.put("user", user);
        ajax.put("roles", roles);
        ajax.put("permissions", permissions);
        ajax.put("isDefaultModifyPwd", initPasswordIsModify(user.getPwdUpdateDate()));
        ajax.put("isPasswordExpired", passwordIsExpiration(user.getPwdUpdateDate()));
        return ajax;
    }

    /**
     * 获取路由信息
     *
     * @return 路由信息
     */
    @GetMapping("getRouters")
    public AjaxResult getRouters() {
        Long userId = SecurityUtils.getUserId();
        List<SysMenu> menus = menuService.selectMenuTreeByUserId(userId);
        return AjaxResult.success(menuService.buildMenus(menus));
    }

    // 检查初始密码是否提醒修改
    public boolean initPasswordIsModify(Date pwdUpdateDate) {
        Integer initPasswordModify = Convert.toInt(configService.selectConfigByKey("sys.account.initPasswordModify"));
        return initPasswordModify != null && initPasswordModify == 1 && pwdUpdateDate == null;
    }

    // 检查密码是否过期
    public boolean passwordIsExpiration(Date pwdUpdateDate) {
        Integer passwordValidateDays = Convert.toInt(configService.selectConfigByKey("sys.account.passwordValidateDays"));
        if (passwordValidateDays != null && passwordValidateDays > 0) {
            if (StringUtils.isNull(pwdUpdateDate)) {
                // 如果从未修改过初始密码，直接提醒过期
                return true;
            }
            Date nowDate = DateUtils.getNowDate();
            return DateUtils.differentDaysByMillisecond(nowDate, pwdUpdateDate) > passwordValidateDays;
        }
        return false;
    }


    @PostMapping("/sendSmsCode")
    public AjaxResult sendSmsCode(@RequestBody LoginBody loginBody) {
        String phoneNum = loginBody.getPhoneNum();
        // 验证手机号
        if (!PhoneUtils.isValidPhone(phoneNum)) {
            return AjaxResult.error("手机号格式不正确");
        }

        // 检查发送频率
        String sendCountKey = CacheConstants.SMS_SEND_COUNT_KEY + phoneNum;
        String count = redisCache.getCacheObject(sendCountKey);
        if (count != null && Integer.parseInt(count) >= 5) {
            return AjaxResult.error("今日验证码发送次数已达上限");
        }

        // 生成验证码
        String smsCode = RandomStringUtils.randomNumeric(6);

        // 发送短信（这里调用实际的短信服务商API）
        boolean sendSuccess = smsService.sendSms(phoneNum, "您的登录验证码是：" + smsCode + "，有效期5分钟。");
        if (!sendSuccess) {
            return AjaxResult.error("短信发送失败，请稍后重试");
        }

        // 保存验证码到Redis，有效期5分钟
        redisCache.setCacheObject(CacheConstants.SMS_CODE_KEY + phoneNum, smsCode, 5, TimeUnit.MINUTES);

        // 记录发送次数，有效期24小时
        redisCache.increment(sendCountKey, 1);
        redisCache.expire(sendCountKey, 24, TimeUnit.HOURS);

        AjaxResult success = AjaxResult.success();
        success.put("smsCode", smsCode);

        return success;
    }


}
